<?php

namespace apiend\modules\download\models;

use Yii;

/**
 * 用户搜索历史记录查询模型
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class KeywordHistorySearch extends \common\models\keyword\KeywordUser implements DownloadExportInterface {

    use DownloadExportTrait;

    public $keyword;

    public function rules() {
        return [
            [['keyword'], 'safe'],
        ];
    }

    /**
     * 绑定过滤条件
     * @param \common\db\ActiveQuery $query
     * @param string $alias
     */
    protected function buildQuery() {
        $query = static::find();
        if ($this->keyword) {
            $condition = [
                'or',
                ['like', 'text', $this->keyword],
            ];
            if (is_numeric($this->keyword)) {
                $condition[] = ['user_id' => $this->keyword];
            }
            $query->andWhere($condition);
        }
        $query->orderBy([
            'updated_at' => SORT_DESC,
            'times' => SORT_DESC,
        ]);
        //$query->debug();
        return $query;
    }

    /**
     * 生成下载文件的名称
     * @return string
     */
    public function exportTitle() {
        return Yii::t('message', '{time}{name}', [
            'time' => date('Y年m月d日H:i:s'),
            'name' => '用户搜索关键词历史记录表',
        ]);
    }

    /**
     * 生成下载文件的名称
     * @return string
     */
    public function exportFileName($ext = true) {
        return Yii::t('message', '{time}-{title}{ext}', [
            'time' => date('Y年m月d日'),
            'title' => '用户搜索关键词历史记录表',
            'ext' => $ext ? '.xlsx' : '',
        ]);
    }

    /**
     * @inheritdoc
     */
    public function exportCaptionOptions() {
        return [];
    }

    /**
     * @inheritdoc
     */
    public function exportFields() {
        return [
            'user_id',
            'text:excelText',
            'times',
            'created_at:datetime',
            'updated_at:datetime',
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'user_id' => '搜索用户ID',
            'text' => '关键字',
            'times' => '检索使用次数',
            'created_at' => '首次搜索时间',
            'updated_at' => '最近搜索时间',
        ];
    }

}
